package com.risetechnology.krystalkitchen1;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import net.simonvt.numberpicker.NumberPicker;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.telephony.cdma.CdmaCellLocation;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.adapter.CustomExpandableListAdapter;
import com.risetechnology.common.Const;
import com.risetechnology.common.Shared;
import com.risetechnology.customviews.CustomFontTextView;
import com.risetechnology.data.Ingredient;
import com.risetechnology.data.Method;
import com.risetechnology.data.Recipe;
import com.risetechnology.master.NavigationActivity;
import com.risetechnology.services.appservices.CountDownManager;
import com.risetechnology.services.appservices.CountDownService;

public class ActivityRecipeDetails extends NavigationActivity {

	private TextView textviewIngredients;
	private LinearLayout frameIngredients;

	private TextView textviewMethod;
	private LinearLayout frameMethod;

	private LinearLayout layoutRate;
	private ImageView imageRate;
	private LinearLayout layoutAdd;
	private LinearLayout layoutFav;
	private ImageView imageFav;
	private boolean isFav = false;

	private TextView textviewRecipeName;
	private TextView textviewServes;
	private TextView textviewDescription;
	private TextView textviewMealType;
	private TextView mTvServingTitle;
	private TextView mTvServingOption;
	private ImageView imageviewImage;

	// private LinearLayout layoutIngredients;
	private TextView textviewPart1Name;
	private LinearLayout layoutPart1Ingredients;

	private TextView textviewPart2Name;
	private LinearLayout layoutPart2Ingredients;

	private TextView textviewPart3Name;
	private LinearLayout layoutPart3Ingredients;

	/*
	 * Method tab
	 */
	private TextView textviewRecipeMethodName;

	private LinearLayout layoutAlarm1;
	private ImageView imageAlarm1;
	private TextView textviewAlarm1;

	private ExpandableListView listviewMethods;
	private CustomExpandableListAdapter methodsListAdapter;
	private List<String> listDataHeader;
	private HashMap<String, List<Method>> listDataChild;

	private long time1 = 0, time2 = 0, time3 = 0;

	private int time = 0;
	private Handler handler;
	private Runnable notification;
	private String DIR_FILE = "";
	private MediaRecorder recorder;

	private LinearLayout layoutAlarm2;
	private ImageView imageAlarm2;
	private TextView textviewAlarm2;

	private LinearLayout layoutAlarm3;
	private ImageView imageAlarm3;
	private TextView textviewAlarm3;

	private Recipe recipe;

	private boolean swap1 = true, swap2 = true, swap3 = true;
	private CountDownManager mCDM;

	private BroadcastReceiver revei = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(CountDownService.ACTION_CDT1_TICK)) {
				onCDT1Tick();
			} else if (action.equals(CountDownService.ACTION_CDT2_TICK)) {
				onCDT2Tick();
			} else if (action.equals(CountDownService.ACTION_CDT3_TICK)) {
				onCDT3Tick();
			} else if (action.equals(CountDownService.ACTION_CDT1_FINISH)) {
				onCDT1Finish();
			} else if (action.equals(CountDownService.ACTION_CDT2_FINISH)) {
				onCDT2Finish();
			} else if (action.equals(CountDownService.ACTION_CDT3_FINISH)) {
				onCDT3Finish();
			}
		}
	};

	private void onCDT1Tick() {
		// if(mCDM.getLastRecipeID1() != recipe.getId()){
		// return;
		// }
		long remaining = mCDM.getCurTime1();

		int addtime = 0;
		if (remaining % 60000 > 0)
			addtime = 1;
		remaining /= 60000; // => minutes
		int hour = (int) remaining / 60;
		int min = (int) remaining % 60 + addtime;

		if (swap1) {
			textviewAlarm1.setText(((hour < 10) ? ("0" + hour) : hour) + " "
					+ ((min < 10) ? ("0" + min) : min));
		} else {
			textviewAlarm1.setText(((hour < 10) ? ("0" + hour) : hour) + ":"
					+ ((min < 10) ? ("0" + min) : min));
		}
		swap1 = !swap1;
	}

	private void onCDT2Tick() {
		// if(mCDM.getLastRecipeID2() != recipe.getId()){
		// return;
		// }
		long remaining = mCDM.getCurTime2();

		int addtime = 0;
		if (remaining % 60000 > 0)
			addtime = 1;
		remaining /= 60000; // => minutes
		int hour = (int) remaining / 60;
		int min = (int) remaining % 60 + addtime;

		if (swap2) {
			textviewAlarm2.setText(((hour < 10) ? ("0" + hour) : hour) + " "
					+ ((min < 10) ? ("0" + min) : min));
		} else {
			textviewAlarm2.setText(((hour < 10) ? ("0" + hour) : hour) + ":"
					+ ((min < 10) ? ("0" + min) : min));
		}
		swap2 = !swap2;
	}

	private void onCDT3Tick() {
		// if(mCDM.getLastRecipeID3() != recipe.getId()){
		// return;
		// }
		long remaining = mCDM.getCurTime3();

		int addtime = 0;
		if (remaining % 60000 > 0)
			addtime = 1;
		remaining /= 60000; // => minutes
		int hour = (int) remaining / 60;
		int min = (int) remaining % 60 + addtime;

		if (swap3) {
			textviewAlarm3.setText(((hour < 10) ? ("0" + hour) : hour) + " "
					+ ((min < 10) ? ("0" + min) : min));
		} else {
			textviewAlarm3.setText(((hour < 10) ? ("0" + hour) : hour) + ":"
					+ ((min < 10) ? ("0" + min) : min));
		}
		swap3 = !swap3;
	}

	private void onCDT1Finish() {
		textviewAlarm1.setText("00.00");
		imageAlarm1.setImageResource(R.drawable.ic_clock_1_off);

		if (mCDM.isRecording()) {
			mCDM.setReady1(true);
		} else {
			Toast.makeText(getBaseContext(), "Playing record 1...",
					Toast.LENGTH_SHORT).show();
			mCDM.playRecord(1);
		}
	}

	private void onCDT2Finish() {
		textviewAlarm2.setText("00.00");
		imageAlarm2.setImageResource(R.drawable.ic_clock_2_off);

		if (mCDM.isRecording()) {
			mCDM.setReady2(true);
		} else {
			Toast.makeText(getBaseContext(), "Playing record 2...",
					Toast.LENGTH_SHORT).show();
			mCDM.playRecord(2);
		}
	}

	private void onCDT3Finish() {
		textviewAlarm3.setText("00.00");
		imageAlarm3.setImageResource(R.drawable.ic_clock_3_off);

		if (mCDM.isRecording()) {
			mCDM.setReady3(true);
		} else {
			Toast.makeText(getBaseContext(), "Playing record 3...",
					Toast.LENGTH_SHORT).show();
			mCDM.playRecord(3);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_recipe_details);

		handler = new Handler();
		DIR_FILE = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/KitchenApp/";
		new File(DIR_FILE).mkdirs();

		recorder = new MediaRecorder();

		// Set contents
		setContents();

		mCDM = TabsManager.mCDM;

		IntentFilter filter = new IntentFilter();
		filter.addAction(CountDownService.ACTION_CDT1_TICK);
		filter.addAction(CountDownService.ACTION_CDT2_TICK);
		filter.addAction(CountDownService.ACTION_CDT3_TICK);
		filter.addAction(CountDownService.ACTION_CDT1_FINISH);
		filter.addAction(CountDownService.ACTION_CDT2_FINISH);
		filter.addAction(CountDownService.ACTION_CDT3_FINISH);
		registerReceiver(revei, filter);
	}

	private void startTimer1(final long milisec) {
		int second = (int) (milisec / 1000);
		int hour = second / 3600;
		int min = (second % 3600) / 60;

		imageAlarm1.setImageResource(R.drawable.ic_clock_1_on);
		textviewAlarm1.setText(((hour < 10) ? ("0" + hour) : hour) + ":"
				+ ((min < 10) ? ("0" + min) : min));

		Toast.makeText(getBaseContext(), "Alarm 1 has been set!",
				Toast.LENGTH_SHORT).show();

		Thread t = new Thread() {
			public void run() {
				while (true) {
					if (Calendar.getInstance().get(Calendar.MILLISECOND) / 10 == 0) {

						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								swap1 = true;
								mCDM.updateCDT1(milisec);
							}
						});
						break;
					}
				}
			}
		};
		t.start();
	}

	private void startTimer2(final long milisec) {
		int second = (int) (milisec / 1000);
		int hour = second / 3600;
		int min = (second % 3600) / 60;

		imageAlarm2.setImageResource(R.drawable.ic_clock_2_on);
		textviewAlarm2.setText(((hour < 10) ? ("0" + hour) : hour) + ":"
				+ ((min < 10) ? ("0" + min) : min));

		Toast.makeText(getBaseContext(), "Alarm 2 has been set!",
				Toast.LENGTH_SHORT).show();

		Thread t = new Thread() {
			public void run() {
				while (true) {
					if (Calendar.getInstance().get(Calendar.MILLISECOND) / 10 == 0) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								swap2 = true;
								mCDM.updateCDT2(milisec);
							}
						});
						break;
					}
				}
			}
		};
		t.start();
	}

	private void startTimer3(final long milisec) {
		int second = (int) (milisec / 1000);
		int hour = second / 3600;
		int min = (second % 3600) / 60;

		imageAlarm3.setImageResource(R.drawable.ic_clock_3_on);
		textviewAlarm3.setText(((hour < 10) ? ("0" + hour) : hour) + ":"
				+ ((min < 10) ? ("0" + min) : min));

		Toast.makeText(getBaseContext(), "Alarm 3 has been set!",
				Toast.LENGTH_SHORT).show();

		Thread t = new Thread() {
			public void run() {
				while (true) {
					if (Calendar.getInstance().get(Calendar.MILLISECOND) / 10 == 0) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								swap3 = true;
								mCDM.updateCDT3(milisec);
							}
						});
						break;
					}
				}
			}
		};
		t.start();
	}

	@SuppressWarnings("deprecation")
	private void showPickTimeDialog(final int pos) {
		if (mCDM.isPlaying()) {
			Toast.makeText(getBaseContext(),
					"Could not set time while play record!", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		if (mCDM.isSelected1() && mCDM.getCurTime1() <= 15000) {
			Toast.makeText(getBaseContext(),
					"Timer 1 ready to start in less than 15s!",
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (mCDM.isSelected2() && mCDM.getCurTime2() <= 15000) {
			Toast.makeText(getBaseContext(),
					"Timer 2 ready to start in less than 15s!",
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (mCDM.isSelected3() && mCDM.getCurTime3() <= 15000) {
			Toast.makeText(getBaseContext(),
					"Timer 3 ready to start in less than 15s!",
					Toast.LENGTH_SHORT).show();
			return;
		}

		final Dialog dialog = new Dialog(
				ActivityRecipeDetails.this.getParent(), R.style.SampleTheme);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_time_picker);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final NumberPicker hp = (NumberPicker) dialog
				.findViewById(R.id.hourPicker);
		hp.setMaxValue(24);
		hp.setMinValue(0);

		final NumberPicker mp = (NumberPicker) dialog
				.findViewById(R.id.minutePicker);
		mp.setMaxValue(59);
		mp.setMinValue(0);

		final NumberPicker sp = (NumberPicker) dialog
				.findViewById(R.id.secondPicker);
		sp.setMaxValue(59);
		sp.setMinValue(0);

		Button btDone = (Button) dialog.findViewById(R.id.btDone);
		btDone.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (hp.getValue() == 0 && mp.getValue() == 0
						&& sp.getValue() == 0) {
					Toast.makeText(getBaseContext(), "Please set time!",
							Toast.LENGTH_LONG).show();
					return;
				}

				if (pos == 1) {
					time1 = hp.getValue() * 3600 + mp.getValue() * 60
							+ sp.getValue();
					time1 *= 1000;

				} else if (pos == 2) {
					time2 = hp.getValue() * 3600 + mp.getValue() * 60
							+ sp.getValue();
					time2 *= 1000;
				} else {
					time3 = hp.getValue() * 3600 + mp.getValue() * 60
							+ sp.getValue();
					time3 *= 1000;
				}

				dialog.dismiss();

				showRecordDialog(pos);
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showRecordDialog(final int pos) {

		final Dialog dialog = new Dialog(
				ActivityRecipeDetails.this.getParent(), R.style.SampleTheme);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_record);
		dialog.setCancelable(false);
		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final TextView rc_time = (TextView) dialog.findViewById(R.id.rc_time);

		TextView rc_name = (TextView) dialog.findViewById(R.id.rc_name);
		if (pos == 1) {
			rc_name.setText("Voice0001");
		} else if (pos == 2) {
			rc_name.setText("Voice0002");
		} else {
			rc_name.setText("Voice0003");
		}

		final ImageButton btRecord = (ImageButton) dialog
				.findViewById(R.id.btRecord);
		btRecord.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!mCDM.isRecording()) {
					// Start record;
					mCDM.setRecording(true);
					time = 0;
					btRecord.setImageResource(R.drawable.ic_stop);
					timeTicker(rc_time);
					onStartRecord(pos);
				} else {
					// Stop record
					if (time < 3)
						return;
					mCDM.setRecording(false);
					handler.removeCallbacks(notification);

					if (pos == 1) {
						mCDM.setLastRecipeID1(recipe.getId());
					} else if (pos == 2) {
						mCDM.setLastRecipeID2(recipe.getId());
					} else {
						mCDM.setLastRecipeID3(recipe.getId());
					}

					onStopRecord(pos);
					dialog.dismiss();
				}

			}
		});

	}

	public void timeTicker(final TextView tv) {
		tv.setText(convertTime(time));
		notification = new Runnable() {
			public void run() {
				time++;
				if (!mCDM.isRecording())
					return;
				timeTicker(tv);
			}
		};
		handler.postDelayed(notification, 1000);
	}

	public String convertTime(int second) {
		// int h = second / 3600;
		int m = (second % 3600) / 60;
		int s = (second % 3600) % 60;
		return /* h+":"+ */((m < 10) ? "0" + m + ":" : m + ":")
				+ ((s < 10) ? "0" + s : s);
	}

	private void onStartRecord(int pos) {
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		recorder.setAudioSamplingRate(16000);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
				.format(new Date()) + ".wav";

		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "SD Card is not mounted. It is" + state + ".",
					Toast.LENGTH_SHORT).show();
			return;
		} else {
			String filePath = DIR_FILE + fileName;
			recorder.setOutputFile(filePath);
			if (pos == 1) {
				mCDM.setFilePath1(filePath);
			} else if (pos == 2) {
				mCDM.setFilePath2(filePath);
			} else {
				mCDM.setFilePath3(filePath);
			}

		}

		try {
			recorder.prepare();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		recorder.start();
	}

	private void onStopRecord(int pos) {
		recorder.stop();
		recorder.reset();

		if (pos == 1) {
			startTimer1(time1);
			mCDM.setSelected1(true);
		} else if (pos == 2) {
			startTimer2(time2);
			mCDM.setSelected2(true);
		} else {
			startTimer3(time3);
			mCDM.setSelected3(true);
		}

		mCDM.checkReadyToPlay();
	}

	private void setContents() {
		int recipeId = getIntent().getIntExtra(Const.KEY_ID, 0);
		recipe = Shared.dbAdapter.getRecipeById(recipeId);

		frameIngredients = (LinearLayout) findViewById(R.id.frame_ingredients);
		frameMethod = (LinearLayout) findViewById(R.id.frame_method);

		textviewIngredients = (CustomFontTextView) findViewById(R.id.tv_ingredients);
		textviewIngredients.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textviewIngredients.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_selected));
				textviewIngredients.setTextColor(getResources().getColor(
						R.color.white));

				textviewMethod.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_normal));
				textviewMethod.setTextColor(getResources().getColor(
						R.color.gray));

				frameIngredients.setVisibility(View.VISIBLE);
				frameMethod.setVisibility(View.GONE);
			}
		});

		textviewMethod = (CustomFontTextView) findViewById(R.id.tv_method);
		textviewMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textviewMethod.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_selected));
				textviewMethod.setTextColor(getResources().getColor(
						R.color.white));

				textviewIngredients.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_normal));
				textviewIngredients.setTextColor(getResources().getColor(
						R.color.gray));

				frameIngredients.setVisibility(View.GONE);
				frameMethod.setVisibility(View.VISIBLE);
			}
		});

		layoutRate = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_rate);
		layoutRate.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showRateDialog();
			}
		});
		imageRate = (ImageView) frameIngredients.findViewById(R.id.iv_rate);
		int rateId = recipe.getRateId();
		imageRate.setImageResource(Const.rateIconId[rateId]);

		layoutAdd = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_add);
		layoutAdd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ActivityRecipeDetails.this
						.getParent(), ActivityAddIngredients.class);
				intent.putExtra(Const.KEY_ID, recipe.getId());
				goNextHistory("Add Ingredients", intent);
			}
		});

		layoutFav = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_fav);
		imageFav = (ImageView) findViewById(R.id.iv_fav);
		isFav = recipe.isFav();
		if (isFav) {
			imageFav.setImageResource(R.drawable.ic_favorite);
		} else {
			imageFav.setImageResource(R.drawable.ic_add_favorite);
		}

		layoutFav.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isFav) {
					isFav = false;
					imageFav.setImageResource(R.drawable.ic_add_favorite);
					Shared.dbAdapter.favRecipe(recipe.getId(), isFav);

					// Update favorite list
					if (!ActivityRecipes.isShowAll) {
						ActivityRecipes.getRecipesFavList();
					}
				} else {
					isFav = true;
					imageFav.setImageResource(R.drawable.ic_favorite);
					Shared.dbAdapter.favRecipe(recipe.getId(), isFav);

					// Update favorite list
					if (!ActivityRecipes.isShowAll) {
						ActivityRecipes.getRecipesFavList();
					}
				}
			}
		});

		textviewRecipeName = (TextView) frameIngredients
				.findViewById(R.id.tv_name);
		textviewRecipeName.setText(recipe.getName());

		textviewServes = (TextView) frameIngredients
				.findViewById(R.id.tv_serves);
		textviewServes.setText(recipe.getServes());

		textviewDescription = (TextView) frameIngredients
				.findViewById(R.id.tv_description_contents);
		textviewDescription.setText(recipe.getMainDescription());

		textviewDescription.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				new ShowTextViewDialog(ActivityRecipeDetails.this.getParent(),
						recipe.getMainDescription());
			}
		});

		textviewMealType = (TextView) frameIngredients
				.findViewById(R.id.tv_meal_type);
		String[] mealTypes = getResources().getStringArray(R.array.meal_types);
		textviewMealType.setText(mealTypes[recipe.getMealType()]);

		imageviewImage = (ImageView) frameIngredients
				.findViewById(R.id.iv_image);
		imageviewImage.setImageDrawable(recipe.getImage());

		/*
		 * Method tab
		 */

		if (recipe.getServingOptions().trim().length() > 0) {
			mTvServingTitle = (TextView) frameMethod
					.findViewById(R.id.tv_serving_title);
			mTvServingTitle.setText("Serving Options");

			mTvServingOption = (TextView) frameMethod
					.findViewById(R.id.tv_serving_option);
			mTvServingOption.setText(recipe.getServingOptions());
		}

		textviewRecipeMethodName = (TextView) frameMethod
				.findViewById(R.id.tv_name);
		textviewRecipeMethodName.setText(recipe.getName());

		layoutAlarm1 = (LinearLayout) frameMethod
				.findViewById(R.id.layout_alarm_1);
		imageAlarm1 = (ImageView) frameMethod.findViewById(R.id.iv_alarm_1);
		textviewAlarm1 = (TextView) frameMethod.findViewById(R.id.tv_alarm_1);
		layoutAlarm1.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showPickTimeDialog(1);
			}
		});

		layoutAlarm2 = (LinearLayout) frameMethod
				.findViewById(R.id.layout_alarm_2);
		imageAlarm2 = (ImageView) frameMethod.findViewById(R.id.iv_alarm_2);
		textviewAlarm2 = (TextView) frameMethod.findViewById(R.id.tv_alarm_2);
		layoutAlarm2.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showPickTimeDialog(2);
			}
		});

		layoutAlarm3 = (LinearLayout) frameMethod
				.findViewById(R.id.layout_alarm_3);
		imageAlarm3 = (ImageView) frameMethod.findViewById(R.id.iv_alarm_3);
		textviewAlarm3 = (TextView) frameMethod.findViewById(R.id.tv_alarm_3);
		layoutAlarm3.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showPickTimeDialog(3);
			}
		});

		// get the listview
		listviewMethods = (ExpandableListView) findViewById(R.id.elv_methods);
		listviewMethods.setGroupIndicator(null);
		listviewMethods
				.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
					@Override
					public boolean onGroupClick(ExpandableListView parent,
							View v, int groupPosition, long id) {
						// Doing nothing
						return true;
					}
				});

		// preparing list data
		prepareListData();

		methodsListAdapter = new CustomExpandableListAdapter(this,
				listDataHeader, listDataChild);

		// setting list adapter
		listviewMethods.setAdapter(methodsListAdapter);

		// Expand list
		int count = methodsListAdapter.getGroupCount();
		for (int i = 0; i < count; i++) {
			listviewMethods.expandGroup(i);
		}

		// TODO

		textviewPart1Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_1_name);
		if (recipe.getPart1Name() == null
				|| recipe.getPart1Name().length() == 0
				|| recipe.getPart1Name().equalsIgnoreCase("Part 1 Name...")) {
			textviewPart1Name.setVisibility(View.GONE);
		} else {
			textviewPart1Name.setText(recipe.getPart1Name());
		}
		layoutPart1Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_1_ingredients);

		for (Ingredient ing : Shared.dbAdapter.getIngByRecipe(recipe.getId(),
				Ingredient.INGRE1)) {
			CustomFontTextView ingredientView = new CustomFontTextView(
					ActivityRecipeDetails.this.getParent());
			ingredientView.setText(ing.toString());
			ingredientView.setTextColor(getResources().getColor(R.color.black));
			layoutPart1Ingredients.addView(ingredientView);
		}

		textviewPart2Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_2_name);
		if (recipe.getPart2Name() == null
				|| recipe.getPart2Name().length() == 0
				|| recipe.getPart2Name().equalsIgnoreCase("Part 2 Name...")) {
			textviewPart2Name.setVisibility(View.GONE);
		} else {
			textviewPart2Name.setText(recipe.getPart2Name());
		}
		layoutPart2Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_2_ingredients);
		for (Ingredient ing : Shared.dbAdapter.getIngByRecipe(recipe.getId(),
				Ingredient.INGRE2)) {
			CustomFontTextView ingredientView = new CustomFontTextView(
					ActivityRecipeDetails.this.getParent());
			ingredientView.setText(ing.toString());
			ingredientView.setTextColor(getResources().getColor(R.color.black));
			layoutPart2Ingredients.addView(ingredientView);
		}

		textviewPart3Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_3_name);
		if (recipe.getPart3Name() == null
				|| recipe.getPart3Name().length() == 0
				|| recipe.getPart3Name().equalsIgnoreCase("Part 3 Name...")) {
			textviewPart3Name.setVisibility(View.GONE);
		} else {
			textviewPart3Name.setText(recipe.getPart3Name());
		}
		layoutPart3Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_3_ingredients);
		for (Ingredient ing : Shared.dbAdapter.getIngByRecipe(recipe.getId(),
				Ingredient.INGRE3)) {
			CustomFontTextView ingredientView = new CustomFontTextView(
					ActivityRecipeDetails.this.getParent());
			ingredientView.setText(ing.toString());
			ingredientView.setTextColor(getResources().getColor(R.color.black));
			layoutPart3Ingredients.addView(ingredientView);
		}
	}

	private void prepareListData() {
		listDataHeader = new ArrayList<String>();
		listDataChild = new HashMap<String, List<Method>>();

		String method1Name = recipe.getPart1MethodName();
		String method1 = recipe.getPart1Method();

		String method2Name = recipe.getPart2MethodName();
		String method2 = recipe.getPart2Method();

		String method3Name = recipe.getPart3MethodName();
		String method3 = recipe.getPart3Method();

		// Part 1
		List<Method> methodPart1 = new ArrayList<Method>();
		if (method1 != null && method1.length() > 0) {
			String[] splittedMethod = method1.split("#");
			if (splittedMethod != null && splittedMethod.length > 0) {
				int length = splittedMethod.length;
				for (int i = 0; i < length; i++) {
					String mt = splittedMethod[i];
					if (mt.length() > 0)
						methodPart1.add(new Method(mt));
				}
			}
		}

		// Part 2
		List<Method> methodPart2 = new ArrayList<Method>();
		if (method2 != null && method2.length() > 0) {
			String[] splittedMethod = method2.split("#");
			if (splittedMethod != null && splittedMethod.length > 0) {
				int length = splittedMethod.length;
				for (int i = 0; i < length; i++) {
					String mt = splittedMethod[i];
					if (mt.length() > 0)
						methodPart2.add(new Method(mt));
				}
			}
		}

		// Part 3
		List<Method> methodPart3 = new ArrayList<Method>();
		if (method3 != null && method3.length() > 0) {
			String[] splittedMethod = method3.split("#");
			if (splittedMethod != null && splittedMethod.length > 0) {
				int length = splittedMethod.length;
				for (int i = 0; i < length; i++) {
					String mt = splittedMethod[i];
					if (mt.length() > 0)
						methodPart3.add(new Method(mt));
				}
			}
		}

		// if (!method1Name.equals("Part 1 Name...")) {
		listDataHeader.add(method1Name);
		listDataChild.put(method1Name, methodPart1);
		// }
		// if (!method2Name.equals("Part 2 Name...")) {
		listDataHeader.add(method2Name);
		listDataChild.put(method2Name, methodPart2);
		// }
		// if (!method3Name.equals("Part 3 Name...")) {
		listDataHeader.add(method3Name);
		listDataChild.put(method3Name, methodPart3);
		// }
	}

	@SuppressWarnings("deprecation")
	private void showRateDialog() {
		final Dialog dialog = new Dialog(ActivityRecipeDetails.this.getParent());

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_rate_recipe);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.BOTTOM;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		LinearLayout layoutYummy = (LinearLayout) dialog
				.findViewById(R.id.layout_yummy);
		layoutYummy.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				imageRate.setImageResource(R.drawable.ic_yummy);
				Shared.dbAdapter.updateRecipeRate(recipe.getId(), 1);
			}
		});

		LinearLayout layoutMmmm = (LinearLayout) dialog
				.findViewById(R.id.layout_mmmm);
		layoutMmmm.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				imageRate.setImageResource(R.drawable.ic_mm);
				Shared.dbAdapter.updateRecipeRate(recipe.getId(), 2);
			}
		});

		LinearLayout layoutMeh = (LinearLayout) dialog
				.findViewById(R.id.layout_meh);
		layoutMeh.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				imageRate.setImageResource(R.drawable.ic_meh);
				Shared.dbAdapter.updateRecipeRate(recipe.getId(), 3);
			}
		});

		LinearLayout layoutYucky = (LinearLayout) dialog
				.findViewById(R.id.layout_yucky);
		layoutYucky.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				imageRate.setImageResource(R.drawable.ic_yucky);
				Shared.dbAdapter.updateRecipeRate(recipe.getId(), 4);
			}
		});

		LinearLayout layoutUnrated = (LinearLayout) dialog
				.findViewById(R.id.layout_unrate);
		layoutUnrated.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				imageRate.setImageResource(R.drawable.ic_unrated);
				Shared.dbAdapter.updateRecipeRate(recipe.getId(), 0);
			}
		});

		dialog.show();
	}

	@Override
	protected void onDestroy() {
		// unregisterReceiver(revei);
		if (null != recorder)
			recorder.release();

		/*
		 * for (File f : new File(DIR_FILE).listFiles()) { f.delete(); }
		 */
		super.onDestroy();
	}
}
